# -*- coding: utf-8 -*-
import os

import pygame
from pygame import Rect

from shared_variables import CONFIG, SCREEN, WHITE


class People:
    def __init__(self, screen, position, image_path):
        self.screen = screen
        self.position = position

        self.image = pygame.transform.scale(pygame.image.load(image_path),
                                            (CONFIG['assets']['office']['temp_potrait_width'],
                                             CONFIG['assets']['office']['temp_potrait_height']))
        self.image_rect = self.image.get_rect()
        self.image_rect.topleft = position

        self.dialogue_start = (self.image_rect.right + 20, self.image_rect.top + 20)
        self.next_dialogue_start = None
        button_path = os.path.join(os.curdir, 'assets/button', f'不聊了.png')
        self.quit_button = pygame.image.load(button_path)

        self.TRANSPARENT_BLUE = (255, 255, 255, 128)  # 半透明的蓝色
        self.button_rect = self.quit_button.get_rect()
        self.button_rect.topleft = (self.image_rect.left, self.image_rect.bottom)  # 放在self.image的正下方，间隔为20像素

        self.dialogue = []

    def draw(self):
        self.screen.blit(self.image, self.image_rect)

        # 显示对话文本
        for index, dialogue_text in enumerate(self.dialogue):
            content = dialogue_text['content']
            if dialogue_text['role'] == 'me':
                if index == 0:
                    self.next_dialogue_start = self.render_text(content, (self.image_rect.right + 300,
                                                                          self.image_rect.top + 20))
                else:
                    self.next_dialogue_start = self.render_text(content, (self.image_rect.right + 300,
                                                                          self.next_dialogue_start.bottom + 20))
            else:
                if index == 0:
                    self.next_dialogue_start = self.render_text(content,
                                                                (self.image_rect.right + 20, self.image_rect.top + 20))
                else:
                    self.next_dialogue_start = self.render_text(content, (self.image_rect.right + 20,
                                                                          self.next_dialogue_start.bottom + 20))

        self.screen.blit(self.quit_button, (self.button_rect.x + 10, self.button_rect.y + 10))

    def render_text(self, text, position) -> pygame.Rect:
        font = pygame.font.SysFont("方正粗黑宋简体", 12)
        lines = []
        current_line = ""
        max_width = 0  # 用于计算最大宽度
        total_height = 0  # 用于计算总高度

        for word in text:
            current_line += word + " "
            if len(current_line) >= 50:
                lines.append(current_line.strip())
                current_line = ""

        if current_line:  # 处理剩余的不足15个字符的部分
            lines.append(current_line.strip())

        rendered_lines = []
        y_offset = position[1]

        # 计算蒙层的大小
        for line in lines:
            rendered_line = font.render(line, True, (0, 0, 0))
            text_rect = rendered_line.get_rect()
            max_width = max(max_width, text_rect.width)
            total_height += text_rect.height
            rendered_lines.append(rendered_line)

        # 创建半透明蒙层
        overlay = pygame.Surface((max_width, total_height), pygame.SRCALPHA)
        overlay.fill((255, 255, 255, 128))  # 白色半透明

        # 绘制蒙层到屏幕
        self.screen.blit(overlay, (position[0], y_offset))

        # 绘制每行文字
        for rendered_line in rendered_lines:
            self.screen.blit(rendered_line, (position[0], y_offset))
            y_offset += rendered_line.get_height()

        # 返回最后一行文字的矩形区域，用于计算下一行文字的位置
        return pygame.Rect(position[0], position[1], max_width, total_height)

    def update_talks(self, dialogue: list):
        self.dialogue = dialogue

    def update_potrait(self, image_name):
        image_path = os.path.join(os.curdir, './assets/portrait/', f"{image_name}.png")

        self.image = pygame.transform.scale(pygame.image.load(image_path),
                                            (CONFIG['assets']['office']['temp_potrait_width'],
                                             CONFIG['assets']['office']['temp_potrait_height']))
        self.image_rect = self.image.get_rect()
        self.image_rect.topleft = self.position

    def handle_event(self, event, callback):
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if self.button_rect.collidepoint(mouse_pos):
                print("点击了: 不聊了")
                callback()
            else:
                pass


if __name__ == '__main__':
    people = People(SCREEN, (200, 100), "D:\work_dir\gameProjects\PyGame\\assets\potrait.png")
    # temp = [{'project_id': 1, 'speak_id': 5, 'role':'me',
    #          'content': '```json\n{\n    "project_describe": "哎呀，热巴啊，这次咱们要搞的可是个大项目——建造一座太空站！你想想看，未来人们在太空中生活、工作，这得是多么酷的一件事啊！再说了，这可是人类探索宇宙的一大步，能参与进来，简直就是荣幸之至啊！",\n    "task_describe": "热巴，我知道你是个大忙人，可是这个任务真的非你莫属啦！你需要负责组装和发射太空站，这可是个技术活，得靠你这双巧手来完成啊！当然了，我会给你提供最好的团队和资源，你就放心大胆地干吧！",\n    "persuade": "热巴啊，我知道你可能会有很多顾虑，比如这个任务有多难，需要付出多少努力和时间等等。但是你想想看，如果成功了，你将成为人类历史上的一位伟大人物！你的名字将被载入史册，被后人传颂不朽！再说了，这也是一个难得的机会，能让你挑战自我，突破自己的极限。我相信你一定能够完成这个任务的，因为你是最棒的！"\n}\n```'}]
    # people.update_talks(temp)
    # while True:
    #     people.draw()
    #     pygame.display.flip()
